package DAL.JDBC;

import java.sql.SQLException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;

public class JedisConn {
	static Jedis jedisConn;
	/* user name and pwd only for local testing*/
	private static final String USER_NAME	= "root";
	private static final String PASSWORD	= "";

	  // private DataSource dataSource;
	   //private JdbcTemplate jdbcTemplateObject;
	   
	static
	{
        //System.out.println("Loading the driver...");
        //Class.forName("com.mysql.jdbc.Driver");
        //System.out.println("Loading successed  ---------------");
        
        String jsonEnvVars = java.lang.System.getenv("VCAP_SERVICES");
        if(jsonEnvVars != null){
			parseUrlFromEnvVarsAndConnect(jsonEnvVars); 
		}
		else{
			jedisConn = new Jedis("localhost");
			//jedisConn.connect();
		}
        createGlobal();

        System.out.println("conn successed. conn=jedis");

}
    private static void parseUrlFromEnvVarsAndConnect(String jsonEnvVars) {
		String url = "";
		try {
			JSONObject jsonObject = new JSONObject(jsonEnvVars);
			JSONArray jsonArray = jsonObject.getJSONArray("redis-2.2");
			jsonObject = jsonArray.getJSONObject(0);
			jsonObject = jsonObject.getJSONObject("credentials");
			String host 	=  jsonObject.getString("host");
			System.out.println("parseUrlFromEnvVarsAndConnect host="+host);
			Integer p = jsonObject.getInt("port");
			String port 	=  p.toString();
			System.out.println("parseUrlFromEnvVarsAndConnect port="+port);
			String dbName 	=  jsonObject.getString("name");
			System.out.println("parseUrlFromEnvVarsAndConnect dbName="+dbName);
			//String username =  jsonObject.getString("username");
			//System.out.println("parseUrlFromEnvVarsAndConnect username="+username);
			String password =  jsonObject.getString("password");
			
			JedisShardInfo jedisShared = new JedisShardInfo(host,Integer.parseInt(port),dbName);
			jedisConn = new Jedis(jedisShared); 
			jedisConn.auth(password);
		} 
		catch (JSONException e) {
			System.err.println("Conn.connect: " + e.getMessage());
		}
	}
    
    private static void createGlobal() {
    	System.out.println("in create global");
		jedisConn.set("global:uid", "1000");
		
		System.out.println("uid = " + jedisConn.get("global:uid"));
	}

	public static Jedis getConnection(){
    	return jedisConn;
    }
}
